﻿using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace WebConversion.Common.WebCache
{
    public sealed class CacheManager : ICacheManager
    {
        #region Singleton

        private static readonly CacheManager _cacheManager = new CacheManager();

        private CacheManager()
        {
        }

        public static CacheManager Instance
        {
            get { return _cacheManager; }
        }

        #endregion

        private readonly Hashtable _cache = Hashtable.Synchronized(new Hashtable());

        public int Count
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get { return _cache.Count; }
        }

        public List<string> AllKeys
        {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get { return (List<string>) _cache.Keys; }
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Add(string key, object value)
        {
            if (_cache.Contains(key))
            {
                _cache[key] = value;
            }
            _cache.Add(key, value);
        }

        public T Get<T>(string key)
        {
            if (_cache.Contains(key))
            {
                return (T) _cache[key];
            }
            return default(T);
        }

        public T Get<T>(string key, InitData initData)
        {
            if (_cache.Contains(key))
            {
                return (T)_cache[key];
            }

            _cache.Add(key, initData());
            return Get<T>(key);
        }

        public void Remove(string key)
        {
            if (_cache.Contains(key))
            {
                _cache.Remove(key);
            }
        }

        public void Clear()
        {
            _cache.Clear();
        }
    }
}

